//接口请求封装模块
import util from "utils.js";

const Data = function() {
  const self = this;
  /**
   * 商品列表字段转换配置
   */
  self.goodsItemField = {
    id:'goods_id',
    image:'goods_thumbnail_url',
    price:'@formatMoney(#price)',
    goods_name:'goods_name',
    coupon_money:'@formatMoney(#coupon_discount)',
    coupon_number:'coupon_remain_quantity',
    promotion_rate:'@formatMoney(#commission)',
    min_normal_price:'lowestPrice',
    min_group_price:'lowestPrice',
    sale_price:'@formatMoney(#lowestPrice)',
    coupon_discount:'coupon_discount',
    buyer:'sold_quantity',
    sales_tip:'sales_tip',
    goods_status:'goods_status',
    album:'album',
    unsale:'unsale',
    platform_type:'platform_type',
    has_coupon:'has_coupon',
    goods_buy_type: 'goods_buy_type'
  };
  /**
   * 商品列表字段转换配置
   */
  self.goodsThemeField = {
    id:'goods_id',
    image:'goods_thumbnail_url',
    price:'@formatMoney(#min_group_price)',
    goods_name:'goods_name',
    coupon_money:'@formatMoney(#coupon_discount)',
    coupon_number:'coupon_remain_quantity',
    promotion_rate:'@formatMoney(#commission)',
    min_normal_price:'min_group_price',
    min_group_price:'min_group_price',
    coupon_discount:'coupon_discount',
    buyer:'sold_quantity',
    sales_tip:'sales_tip',
  };
  /**
   * 商品列表字段转换配置
   */
  self.goodsShoopField = {
    id:'goods_id',
    image:'goods_thumbnail_url',
    price:'@formatMoney(#goods_fact_price)',
    goods_name:'goods_name',
    coupon_money:'@formatMoney(#coupon_discount)',
    coupon_number:'coupon_remain_quantity',
    promotion_rate:'@formatMoney(#commission)',
    min_normal_price:'goods_fact_price',
    min_group_price:'goods_fact_price',
    coupon_discount:'coupon_discount',
    buyer:'sold_quantity',
    sales_tip:'sales_tip',
  };

  /**
   * 快速格式化字段
   * @param config 置换配置顶
   * @param data 主数据体
   * @param _single bool 是否处理单元素
   * @returns {Array}
   * 示例
   * {
   *     image(返回字段):url(原始字段),
   *     price:@formatMoney(#min_price,*field)  @+unit下的函数名 #+原始字段名 *+返回字段名
   * }
   */
  self.formatData = function(config,data,_single){
    let temp   = [],item;
    let single = _single || false;
    let parts,param,value,reg;
    if(!config){
      return data;
    }
    if(single === true){
      data = [data];
    }
    for(let i=0;i<data.length;i++){
      item  = {};
      for(let key in config){
        parts = {};
        param = {};
        value = null;
        reg   = /\\*@([^@#%&()\?\s]+)(?:\((.*?)\))?/g;
        if(config.hasOwnProperty(key)){
          if(config[key].indexOf('@') === 0){
            parts = reg.exec(config[key]);
            if(parts && parts.length > 2 && util.hasOwnProperty(parts[1])){
              param = parts[2].split(/,\s*/);
              for(let f=0;f<param.length;f++){
                if(param[f].substring(0,1) === '#'){
                  param[f] = data[i][param[f].replace('#','')];
                  continue;
                }
                if(param[f].substring(0,1) === '*'){
                  param[f] = item[param[f].replace('*','')];
                }
              }
              value = util[parts[1]].apply(this,param);
              item[key] = value;
            }
            continue;
          }
          item[key] = data[i][config[key]];
        }
      }
      temp.push(item);
    }
    if(single === true){
      temp = temp[0];
    }
    return temp;
  };
  /**
   * 获取推荐块数据
   */
  self.GetRecommendList = function(type,callback, up,load) {
    let update  = up || false;
    let c_key   = 'recommendList_' + type;
    let loading = load || true;
    let res     = util.cache_get(c_key, false);
    if (!res || update !== false) {
      util.request({
        url: util.api.GetRecommendList,
        data:{
          platform_type:type
        },
        loading:loading,
        callback: function(result) {
          util.cache_put(c_key, result.res.recommend,3600);
          result.res['isNetWork'] = true;
          callback && callback.call(this, result.res.recommend);
        },
        error:function () {
          callback && callback.call(this, false);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 获取商品详情
   * @param param
   * @param callback
   * @param up
   * @param loading
   */
  self.getGoodsDetail = function(param, callback, up,loading) {
    util.request({
      url: util.api.getGoodsDetail,
      data: param,
      loading: loading || true,
      callback: function(result) {
        let goods_detail = {};
        if (result.res.goods_detail) {
          let or_detail = result.res.goods_detail;
          goods_detail = self.formatData({
            goods_id:'goods_id',      //ID
            coupon_discount:'coupon_discount',      //优惠券面额
            coupon_start_time:'coupon_start_time',  //优惠券开始时间
            coupon_end_time:'coupon_end_time',      //优惠券结束时间
            images:'goods_gallery_urls',
            thumb:'goods_image_url',
            title:'goods_name',
            has_coupon:'has_coupon',                 //是否有优惠券
            mall_id:'mall_id',
            mall_name:'mall_name',
            mall_goods_total:'mall_goods_total',
            price:'@formatMoney(#lowestPrice)',      //最低价
            min_normal_price:'lowestPrice',          //最低正常价
            money:'@formatMoney(#price)',            //原价
            coupon_number:'coupon_remain_quantity',  //优惠券数量
            save_money: '@formatMoney(#save_money)',
            promotion_rate:'@formatMoney(#commission)',
            buyer:'sold_quantity',
            sales_tip:'sales_tip',
            commission:'@formatMoney(#commission)',
            team_commission:'@formatMoney(#team_commission)',
            platform_type:'platform_type',
            is_collection:'is_collection',
            unsale: 'unsale',
            peaAmount:'pea_amount'
          }, or_detail,true);

          if(goods_detail['has_coupon']){
            goods_detail['coupon_discount'] = util.formatMoney(goods_detail['coupon_discount']);
          }
          goods_detail['buyer'] = (goods_detail['buyer'] < 1000 && goods_detail['buyer'] > 0) ? goods_detail['buyer'] : goods_detail['sales_tip'];
          goods_detail['user'] = result.res.userAvatar;
          //统计信息
          goods_detail['statistical_data'] = result.res.statistical_data;
          // if(goods_detail.hasOwnProperty('platform_type') && util.fixInt(goods_detail['platform_type']) === 2){
          //   goods_detail['unsale'] = true;
          // }
          callback && callback(goods_detail);
        }else{
          callback && callback(false);
        }
      }
    });
  };
  /**
   * 获取我的收藏
   */
  self.getLove = function(callback, p, up) {
    let update = up || false;
    let page   = p || 1;
    let c_key  = 'my_love';
    let res    = util.cache_get(c_key, false);
    //只缓存第一页,第二页永远从网络请求
    if(page > 1){
      res = false;
    }
    if (!res || update !== false) {
      util.request({
        url: util.api.followData,
        data: {
          page: page,
          limit:10
        },
        callback: function(result) {
          let pop = {
            data:[],
            total:0
          };
          //处理统一的数据结构
          try{
            if(result['res']['list']){
              pop['data']  = self.formatData(self.goodsItemField,result['res']['list']);
              pop['total'] = result['res']['total'];
            }
          }catch (e) {

          }
          util.cache_put(c_key, pop, 20);
          callback && callback.call(this, pop);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 获取我的历史
   */
  self.getHistory = function(callback, p, up) {
    let update = up || false;
    let page   = p || 1;
    let c_key  = 'my_history';
    let res    = util.cache_get(c_key, false);
    //只缓存第一页,第二页永远从网络请求
    if(page > 1){
      res = false;
    }
    if (!res || update !== false) {
      util.request({
        url: util.api.historyData,
        data: {
          page: page,
          limit:10
        },
        callback: function(result) {
          let pop = {
            data:[],
            total:0
          };
          //处理统一的数据结构
          try{
            if(result['res']['list']){
              pop['data']  = self.formatData(self.goodsItemField,result['res']['list']);
              pop['total'] = result['res']['total'];
            }
          }catch (e) {

          }
          util.cache_put(c_key, pop, 20);
          callback && callback.call(this, pop);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 获取商店商品列表
   * @param id int
   * @param platform int
   * @param callback
   * @param p
   * @param up
   */
  self.getMailGoods = function(id,platform,callback, p, up) {
    let self = this;
    util.request({
      url: util.api.getMailGoods,
      data: {
        platform_type:platform,
        mall_id:id,
        page_size:40,
        page: 1
      },
      callback: function(result) {
        let pop = {
          data:[],
          total:0
        };
        let _data = [];
        //处理统一的数据结构
        if(result['res']['goods_list']){
          _data  = self.formatData(self.goodsItemField,result['res']['goods_list']);
          /**
           * 过滤没有券的商品
           */
          for(let i=0;i<_data.length;i++){
            if(_data[i]['has_coupon']){
              pop['data'].push(_data[i]);
            }
          }
          pop['total'] = pop['data'].length;
        }
        /**
         * 强制为1
         */
        pop['total'] = pop['total'] === 0 ? 1 : pop['total'];
        callback && callback.call(this, pop);
      }
    });
  };
  /**
   * 获取用户收货地址
   * @param callback
   * @param p
   * @param up
   */
  self.getUserAddress = function(data,callback, p, up) {
    let update = up || false;
    let page   = p || 1;
    let c_key  = 'u_address_' + '_' + p;
    let res = util.cache_get(c_key, false);
    //只缓存第一页,第二页永远从网络请求
    if(page > 1){
      res = false;
    }
    if (!res || update !== false) {
      util.request({
        url: util.api.userAddress,
        data:data,
        callback: function(result) {
          let pop = {
            data:[],
            total:0
          };
          //处理统一的数据结构
          if(result['res']['list']){
            pop['data']  = result['res']['list'];
          }
          util.cache_put(c_key, pop,7200);
          callback && callback.call(this, pop);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 热门搜索关键词
   */
  self.getHotSearch = function(callback, up) {
    let update = up || false;
    let c_key  = 'hot_search';
    let res = util.cache_get(c_key, false);
    if (!res || update !== false) {
      util.request({
        url: util.api.searchHot,
        loading:1,
        callback: function(result) {
          util.cache_put(c_key, result.res,7200);
          callback && callback.call(this, result.res);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 获取提现信息
   */
  self.GetBankCard = function(callback, up) {
    let update = up || false;
    let c_key  = 'user_bankcard';
    let res = util.cache_get(c_key, false);
    if (!res || update !== false) {
      util.request({
        url: util.api.GetBankCard,
        loading:1,
        callback: function(result) {
          util.cache_put(c_key, result.res,7200);
          callback && callback.call(this, result.res);
        },
        error:function () {
          callback && callback.call(this, false);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 生成分享信息
   */
  self.QrcodeUrlShera = function(param,callback) {
      util.request({
        url: util.api.QrcodeUrlShera,
        data:param,
        handle:true,
        loading:false,
        callback: function(result) {
          callback && callback(result);
        }
      });
  };
  /**
   * 统一格式化商品列表数据
   * @param data
   * @param platformType
   */
  self.formatGoodsList = function (data, platformType) {
    for(let i=0;i<data.length;i++){
      /**
       * 试算券后价格
       * @type {number}
       */
      /**
       * 销量显示问题
       */
      data[i]['buyer'] = (data[i]['buyer'] < 1000 && data[i]['buyer'] > 0) ? data[i]['buyer'] : data[i]['sales_tip'];
      // 商品平台类型
      data[i]['coupon_number'] = 1;
      if(!data[i].hasOwnProperty('platform_type') && platformType){
        data[i]['platform_type'] = platformType;
      }
      if(!data[i].hasOwnProperty('sale_price') && platformType){
        data[i]['sale_price'] = util.formatMoney(data[i]['min_group_price'] - data[i]['coupon_discount']);
      }
      data[i]['unsale_text'] = '';
      if(data[i].hasOwnProperty('unsale') && data[i]['unsale'] === true){
        data[i]['unsale_text'] = '商品已下架，无法查看';
      }
      /**
       * 淘宝商品处理为下架
       */
      // if(data[i].hasOwnProperty('platform_type') && util.fixInt(data[i]['platform_type']) === 2){
      //   data[i]['unsale']      = true;
      //   data[i]['unsale_text'] = '淘宝商品不支持小程序展示，请下载APP体验';
      // }
    }
    return data;
  };
  /**
   * 申请高级管家
   */
  self.sendSms = function (data, callback) {
    util.request({
      url: util.api.sendSms,
      data: data,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
  // 获取管家审核状态
  self.getGroupStatus = function(callback){
    util.request({
      url: util.api.getGroupStatus,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
  self.getDictConfig = function(type,callback, up) {
    let update = up || false;
    let c_key  = 'dict_' + type;
    let res = util.cache_get(c_key, false);
    if (!res || update !== false) {
      util.request({
        loading:2,
        url:util.api.GetDict,
        data:{
          label:type
        },
        callback:function (result) {
          let app = getApp();
          util.cache_put(c_key, result.res,600);
          if(result.hasOwnProperty('res')){
            app.globalData[type] = result.res;
          }
          console.log(app.globalData);
          callback && callback.call(this, result.res);
        },
        error:function () {
          callback && callback.call(this, false);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 获取分类信息
   * @param platform
   * @param callback
   * @param up
   */
  self.getCategory = function(platform,callback,up){
    let update = up || false;
    let c_key  = 'category_' + platform;
    let res = util.cache_get(c_key, false);
    let level = 2;
    if(util.fixInt(platform) === 3){
      level = 1;
    }
    if (!res || update !== false) {
      util.request({
        url:util.api.GetGoodsOpts,
        data:{
          platform_type:platform,
          level:level
        },
        callback:function (result) {
          let cate = self.formatCategory(platform,result.res.goods_opts);
          util.cache_put(c_key, cate);
          callback && callback.call(this, cate);
        },
        error:function () {
          callback && callback.call(this, false);
        }
      });
    } else {
      callback && callback.call(this, res);
    }
  };
  /**
   * 格式化分类数据
   * @param type
   * @param data
   * @returns {Array}
   */
  self.formatCategory = function(type,data){
    let result = [];
    let child,item,c_item;
    let parent = 1;
    if(!data){
      return result;
    }
    if(util.fixInt(type) === 3){
      parent = 0;
    }
    for(let i=0;i<data.length;i++){
      item = {};
      if(data[i]['level'] !== parent){
        continue;
      }
      item['id']   = data[i]['opt_id'];
      item['name'] = data[i]['alias'] !== '' ? data[i]['alias'] : data[i]['opt_name'];
      item['list_order'] = util.fixInt(data[i]['list_order']) + 1;
      item['child'] = [];
      if(data[i]['goods_opts_list'] && data[i]['goods_opts_list'].length > 0){
        for(let j = 0;j<data[i]['goods_opts_list'].length;j++){
          c_item = data[i]['goods_opts_list'][j];
          child  = {};
          child['id']    = c_item['opt_id'];
          child['image'] = c_item['thumb'];
          child['name']  = c_item['alias'] !== '' ? c_item['alias'] : c_item['opt_name'];
          child['list_order'] = util.fixInt(c_item['list_order']) + 1;
          item['child'].push(child);
        }
        item['child'].sort(function (a,b) {
          return a.list_order - b.list_order;
        });
      }
      result.push(item);
    }
    result.push({
      id:1,
      name:'热门',
      list_order:0,
      child:[]
    });
    result.sort(function (a,b) {
      return a.list_order - b.list_order;
    });
    util.cache_put('category_format_' + type,result);
    return result;
  };
  // 获取附近门店
  self.getRecommendStores = function (data, callback) {
    util.request({
      url: util.api.recommendStores,
      data: data,
      callback: function(result) {
        callback && callback.call(this, result.res);
      },
      error:function () {
        callback && callback.call(this, false);
      }
    });
  };
  /**
* 获取当前门店信息
* @param data
* @param callback
*/
  self.GetStoreInfo = function (data, callback) {
    util.request({
      url: util.api.GetStoreInfo,
      data: data,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
  /**
* 门店搜索
* @param data
* @param callback
*/
  self.YddSearchStores = function (data, callback) {
    util.request({
      url: util.api.YddSearchStores,
      data: data,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
  /**
  * 门店搜索
  * @param data
  * @param callback
  */
  self.ActiveAddr = function (data, callback) {
    util.request({
      url: util.api.ActiveAddr,
      data:data,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
  /**
   * 格式化分类数据
   * @param type
   * @param data
   * @returns {Array}
   */
  self.GetStoreInfo = function (data, callback) {
    util.request({
      url: util.api.GetStoreInfo,
      data: data,
      handle: true,
      loading: true,
      callback: function (result) {
        callback && callback(result);
      }
    });
  };
};
module.exports = new Data();
